package cn.itsource.basic.base.service.impl;

import cn.itsource.basic.base.domain.RegisterDto;
import cn.itsource.basic.base.service.IVerifyCodeService;
import cn.itsource.basic.exception.CustomException;
import cn.itsource.basic.exception.ErrorCode;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.basic.util.VerifyCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Override
    public AjaxResult imgCode(String uuid) {
        //生成随机字符串
        String code = StrUtils.getComplexRandomString(4);
        //生成图片验证码得base64
        String base64 = VerifyCodeUtils.VerifyCode(120, 40, code);
        //保存redis设置过期时间3分钟
        redisTemplate.opsForValue().set(uuid,code,180000, TimeUnit.MILLISECONDS);
        //封装AjaxResult返回对象
        return AjaxResult.me().setResultObj(base64);
    }

    @Override
    public AjaxResult sendSmsCode(RegisterDto dto) {
        //把所有参数取出来
        String imgKey = dto.getImgKey();
        String phone = dto.getPhone();
        String imageCode = dto.getImageCode();
        //查询图形验证码
        Object redisImgCode = redisTemplate.opsForValue().get(imgKey);
        //没查到图形验证码
        if(redisImgCode == null){
            throw new CustomException(ErrorCode.IMG_CODE_EXPIRE.getCode());
        }
        //如果判断输入的和redis中取出来得不一致
        if(!redisImgCode.toString().equalsIgnoreCase(imageCode)){
            throw new CustomException(ErrorCode.IMG_CODE_ERROR.getCode());
        }
        //准备发送短信
        String smsCodeKey = "smsCode:"+phone;
        Object redisSmsValue = redisTemplate.opsForValue().get(smsCodeKey);
        //公共短信验证码变量
        String smscode;
        if(redisSmsValue == null){
            smscode = StrUtils.getRandomString(6);
        }else{
            //判断是否已过重发时间
            String[] values = redisSmsValue.toString().split(":");
            //获取发送时得时间戳
            long sendTime = Long.parseLong(values[1]);
            //获取当前时间戳
            long currentTime = System.currentTimeMillis();
            //判断是否已过重发时间
            long timeDi =  currentTime - sendTime;
            if(timeDi < 60000){
                throw new CustomException(ErrorCode.TIME_NOT_ARRIVED.getCode());
            }
            smscode = values[0];
        }
        //发送短信
        log.info("您本次得验证码是{}",smscode);
        //如果首次发存储redis 如果不是首次刷新过期时间
        redisTemplate.opsForValue().set(smsCodeKey,smscode+":"+System.currentTimeMillis(),300000,TimeUnit.MILLISECONDS);
        return AjaxResult.me();
    }

}
